package com.leetcode.array_matrix;

import java.util.Stack;

/**
 * @author Dennis Li
 * @date 2020/10/25 16:07
 */
public class LongestMountain_845 {

    public int longestMountain(int[] A) {
        Stack<Integer> stack = new Stack<>();
        int ans = 0;
        boolean ascend = true;
        stack.push(0);
        for (int i = 1; i < A.length; i++) {
            if (A[i - 1] == A[i]) {
                stack.clear();
                stack.push(i);
                ascend = true;
            } else if (stack.isEmpty() || (ascend && A[i - 1] < A[i])) {
                stack.push(i);
            } else if (ascend && A[i - 1] > A[i]) {
                ascend = false;
                ans = Math.max(i - stack.pop(), ans);
            } else if (!stack.isEmpty() && !ascend && A[i - 1] > A[i]) {
                ans = Math.max(i - stack.pop(), ans);
            } else if (!ascend && A[i - 1] < A[i]) {
                ans = Math.max(i - stack.pop(), ans);
                stack.clear();
                stack.push(i);
                ascend = true;
            }
        }
        return ans;
    }

    public int longestMountain2(int[] A) {
        int res = 0;
        if (A.length == 0) {
            return res;
        }
        int l = 0, r = 0;
        while (r < A.length) {
            while (r + 1 < A.length && A[r + 1] > A[r]) {          //尝试“上山”
                r++;
            }
            int temp = r;                              //用于之后判断是否经历“下山”

            while (r > l && r + 1 < A.length && A[r + 1] < A[r]) {     //尝试“下山”
                r++;
            }

            if (r == temp) {                      //如果r没有“下山”都不符合要求，指针后移
                r++;
            } else {                          //存在山脉时与已有结果比较取大值，r、l后移
                res = Math.max(res, r - l + 1);
            }
            l = r;
        }
        return res;
    }


}
